﻿using System;
using System.Collections.Generic;
using LiveChartsCore;
using LiveChartsCore.Drawing;
using LiveChartsCore.Kernel;
using LiveChartsCore.SkiaSharpView.Drawing;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Painting;
using SkiaSharp;

namespace TestWpfLiveCharts2.Extensions
{
    public class CropRangePaintBuilder<TModel, TVisual, TLabel, TDrawingContext>
        where TDrawingContext : DrawingContext
        where TVisual : class, IVisualChartPoint<TDrawingContext>, new()
        where TLabel : class, ILabelGeometry<TDrawingContext>, new()
    {
        public CropRangePaintBuilder(Series<TModel, TVisual, TLabel, TDrawingContext> series, IPaint<TDrawingContext> paint)
        {
            _series = series;
            _paint = paint;
        }

        private readonly Series<TModel, TVisual, TLabel, TDrawingContext> _series;
        private readonly IPaint<TDrawingContext> _paint;
        private Func<ChartPoint<TModel, TVisual, TLabel>, bool>? _whenPredicate;

        public Series<TModel, TVisual, TLabel, TDrawingContext> When(
            Func<ChartPoint<TModel, TVisual, TLabel>, bool> predicate)
        {
            _whenPredicate = predicate;
            _series.DataPointerDown += Series_DataPointerDown;
            return _series;
        }

        public void Unsubscribe()
        {
            _series.DataPointerDown -= Series_DataPointerDown;
        }

        private void Series_DataPointerDown(LiveChartsCore.Kernel.Sketches.IChartView chart
            , IEnumerable<ChartPoint<TModel, TVisual, TLabel>> points)
        {
            if (_whenPredicate is null) return;

            foreach (var jp in points)
            {
                var isTriggered = _whenPredicate.Invoke(jp);
                if (isTriggered
                    && jp.Visual is Geometry tg)
                {
                    if (tg.Fill is null)
                    {
                        tg.Fill = _paint as IPaint<SkiaSharpDrawingContext>;
                    }
                    else
                    {
                        tg.Fill = null;
                    }
                }
            }
            chart.Invalidate();  // 请求重绘
        }
    }
}